package com.pig4cloud.pig.village.file.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.village.api.entity.VillageImage;
import com.pig4cloud.pig.village.file.mapper.ImageMapper;
import com.pig4cloud.pig.village.file.service.IFileService;
import com.pig4cloud.pig.village.file.service.IImageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author limbray.li
 * @date 2021/6/26
 */
@Service
@Slf4j
public class ImageServiceImpl extends ServiceImpl<ImageMapper, VillageImage> implements IImageService {
	@Resource
	private IFileService fileService;
	@Override
	public boolean saveFiles(Integer type, Long key, MultipartFile[] files) {
		List<VillageImage> images = new ArrayList<>();
		VillageImage image;
		//1：文件保存到对象服务器
		for (MultipartFile file : files) {
			image = VillageImage.builder()
					.outKey(key)
					.type(type)
					.url(filesSaveToOSS(file))
					.fileName(file.getOriginalFilename())
					.build();
			images.add(image);
		}
		//2：先删除文件
		LambdaQueryWrapper<VillageImage> query = Wrappers.lambdaQuery();
		query.eq(VillageImage::getOutKey,key);
		query.eq(VillageImage::getType,type);
		super.remove(query);
		//3：信息保存到数据库
		super.saveBatch(images);
		return true;
	}

	@Override
	public boolean saveFiles(Integer type, Long key, MultipartFile file) {
		List<VillageImage> images = new ArrayList<>();
		//1：文件保存到对象服务器
		VillageImage image = VillageImage.builder()
				.outKey(key)
				.type(type)
				.url(filesSaveToOSS(file))
				.fileName(file.getOriginalFilename())
				.build();
		images.add(image);
		//2：信息保存到数据库
		super.saveBatch(images);
		return true;
	}


	private String filesSaveToOSS(MultipartFile file) {
		return fileService.uploadFile(file);
	}

	@Override
	public List<VillageImage> getImages(Integer type, Collection<Long> keys) {
		LambdaQueryWrapper<VillageImage> query = Wrappers.lambdaQuery();
		query.in(CollectionUtils.isNotEmpty(keys), VillageImage::getOutKey, keys);
		query.eq(type != null, VillageImage::getType, type);
		return super.list(query);
	}

	@Override
	public VillageImage getImageByObjectName(String objectName) {
		LambdaQueryWrapper<VillageImage> query = Wrappers.lambdaQuery();
		query.eq( VillageImage::getUrl, objectName);
		return super.getOne(query);
	}

	//TODO 待删除图片
}
